var express = require('express');
var router = express.Router();
var jwt = require("jsonwebtoken")
const CryptoJS = require("crypto-js");
let { xinModel,
  userlistModel } = require('../modu/jfq')
/* GET home page. */
function encryptMD5(password) {
  return CryptoJS.MD5(password).toString();
}
router.post("/register", async (req, res) => {
  try {
    // 检查是否包含username和password字段
    if (!req.body.username || !req.body.password) {
      return res.send({ msg: "缺少用户名或密码", code: 400 });
    }

    // 查询用户是否存在
    const user = await userlistModel.findOne({ username: req.body.username });

    if (user) {
      return res.send({ msg: "该用户已经注册", code: 201 });
    } else {
      // 创建新用户
      const username = req.body.username;
      const password = encryptMD5(req.body.password);
      const newUser = await userlistModel.create({ username, password });
      const newJuese = await xinModel.create({
        username: username,
        img: "https://ts1.cn.mm.bing.net/th?id=OIP-C.6ZyK9nSZH54IassCkWHzIgAAAA&w=250&h=250&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2"
      });
      // 将新用户的_id添加到jueseModel中的uid字段中
      newJuese.uid = newUser._id;
      await newJuese.save();

      res.send({ msg: "注册成功", code: 200 });
    }
  } catch (error) {
    console.error("Error: ", error);
    res.status(500).send({ msg: "服务器错误", code: 500 });
  }
});



router.post("/login", async (req, res) => {
  let body = req.body
  console.log(req.body);
  let userlist = await userlistModel.find({ username: body.username });
  let usedata = await xinModel.find({ usepid: userlist[0]._id })
  if (userlist.length == 0) {
    res.send({
      code: 201,
      msg: "用户没注册"
    })
  } else {
    let password = encryptMD5(body.password);
    if (userlist[0].password == password) {
      let token = "Bearer " + jwt.sign(body, "hc", { expiresIn: "1d" });
      res.send({
        usedata,
        code: 200,
        msg: "登录成功",
        token,
      });
    } else {
      res.send({
        code: 202,
        msg: "密码错误"
      });
    }
  }
});




// router.get('/getlist',async (req,res)=>{
//     let data=await roleModel.find().populate('rid')
//     res.send({
//         data
//     })
// })

// //发送短信验证码
// router.post("/send", async (req, res) => {
//     let data = req.body;
//     let phone = data.phone;
//     //随机验证码

//     //下载引入tengcentcloud插件
//     const tencentcloud = require("tencentcloud-sdk-nodejs-sms");
//     const SmsClient = tencentcloud.sms.v20210111.Client;

//     // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
//     // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
//     // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
//     const clientConfig = {
//       credential: {
//         secretId: "AKIDtfXOm25vXyBJWIrAHCsJYZLs9GDvPl6L", //创建api的id
//         secretKey: "GSmxlimv8Y4eCkLyjjmv43rdIwXxCMXp", //创建api的key
//       },
//       region: "ap-beijing", //接口地域
//       profile: {
//         httpProfile: {
//           endpoint: "sms.tencentcloudapi.com",
//         },
//       },
//     };
//     // 实例化要请求产品的client对象,clientProfile是可选的
//     const client = new SmsClient(clientConfig);
//     const params = {
//       PhoneNumberSet: ["+86" + phone], //添加+86地区的手机号
//       SmsSdkAppId: "1400879043", //添加应用后的实际id
//       SignName: "zhao的赵公众号", //发送允许的签名
//       TemplateId: "2039914", //发送允许的模版id
//       TemplateParamSet: [randomNumber], //发送的短信 必须是字符串的形式
//     };
//     client.SendSms(params).then(
//       (data) => {
//         console.log(data);
//       },
//       (err) => {
//         console.error("error", err);
//       }
//     );
//     res.send("ok");
//   });



module.exports = router;